package com.whz.work;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName ServerSocketDemo
 * @Description TODO ServerSocket
 * 服务器套接字要等待来自客户端的连接请求
 * 当服务套接字收到了连接请求后,它会创建一个Socket实例来处理与客户端的通信
 * @Author hong-zhi
 * @Date 2021/5/27 17:08
 * @Version 1.0
 */
@Slf4j
public class ServerSocketDemo {
    public static void server(String host, int port, int backlog) {
        try {
            ServerSocket ss = new ServerSocket(port, backlog, InetAddress.getByName(host));
            Socket socket = ss.accept();
            /*在控制台打印接收到的请求内容*/
            InputStream is = socket.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));


            boolean loop = true;
            StringBuffer sb = new StringBuffer(8096);
            while (loop) {
                if(in.ready()) {
                    int i = 0;
                    while (i != -1) {
                        i = in.read();
                        sb.append((char) i);
                    }
                    loop = false;
                }
            }
            log.info("接收到的请求数据:");
            log.info(sb.toString());

        } catch (IOException e) {
            log.error("找不到指定IP: {}", host);
        }
    }
}
